package com.hly.musicbackground.model.movies.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hly.musicbackground.Final.MoviesLinkFinal;
import com.hly.musicbackground.dao.MoviesLinkDao;
import com.hly.musicbackground.domain.MoviesLink;
import com.hly.musicbackground.model.movies.params.MoviesLinkParams;
import com.hly.musicbackground.model.movies.service.MoviesLinkService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MoviesLinkServiceImpl extends ServiceImpl<MoviesLinkDao, MoviesLink> implements MoviesLinkService {



    @Override
    public MoviesLink getAutoMoviesLink(int uid, int mid) {
        MoviesLink one = lambdaQuery().eq(MoviesLink::getUserId, uid)
                .eq(MoviesLink::getMoviesId, mid)
                .one();
        if (one == null){
            one = MoviesLink.builder()
                    .moviesId(mid)
                    .userId(uid)
                    .numEpisodes(0)
                    .type(MoviesLinkFinal.foot)
                    .build();
            save(one);
        }
        return one;
    }

    @Override
    public void emitMoviesLink(MoviesLinkParams params, int uid) {
        MoviesLink one = lambdaQuery()
                .eq(MoviesLink::getMoviesId, params.getMoviesId())
                .eq(MoviesLink::getUserId, uid)
                .one();

        if (one == null){
            one = MoviesLink.builder()
                    .type(params.getType())
                    .numEpisodes(params.getNumEpisodes())
                    .userId(uid)
                    .moviesEpisodesId(params.getMoviesEpisodesId())
                    .moviesId(params.getMoviesId())
                    .build();
            save(one);
        }else {
            one.setMoviesEpisodesId(params.getMoviesEpisodesId());
            one.setNumEpisodes(params.getNumEpisodes());
            one.setType(params.getType());
            one.setUpdateTime(new Date());
            updateById(one);
        }
    }

    @Override
    public List<MoviesLink> getMoviesLinkList(int limit, int page, int type, int uid) {
        List<MoviesLink> records = lambdaQuery()
                .eq(MoviesLink::getUserId, uid)
                .eq(MoviesLink::getType, type)
                .page(new Page<>(page, limit)).getRecords();
        return records;
    }

    @Override
    public void delMoviesLink(int uid, List<String> moviesIds) {
        remove(Wrappers.<MoviesLink>lambdaQuery()
                .in(MoviesLink::getUserId, uid)
                .in(MoviesLink::getMoviesId, moviesIds));
    }
}
